package com.webserver.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class HttpServletRequest {
    private Socket socket;
    //请求行信息
    private String method;
    private String uri;
    private String protocol;//协议版本

    private String requestURI;
    private String queryString;//保存uri中?号右侧的get的内容
    private Map<String,String> parameters=new HashMap<>();
    //消息头相关信息
    private Map<String,String> headers=new HashMap<>();

    public HttpServletRequest(Socket socket) throws IOException, EmptyRequestException {
        this.socket=socket;
        parseRequestLine();
        parseHeaders();
        parseContent();
    }

    /**
     * 解析请求行
      */
    private void parseRequestLine() throws IOException, EmptyRequestException {
        String line;
        line=readLine();
        if (line.isEmpty()){
            throw new EmptyRequestException();
        }
        System.out.println("请求行: "+line);
        String[] array=line.split("\\s");
//            method=line.substring(0,line.indexOf(" "));
//            uri=line.substring(line.indexOf(" ")+1,line.lastIndexOf(" "));
//            protocol=line.substring(line.lastIndexOf(" ")+1);
        method=array[0];
        uri=array[1];
        protocol=array[2];
        parseUri();//进一步解析uri
        System.out.println("method: "+method);
        System.out.println("uri: "+uri);
        System.out.println("protocol: "+protocol);
    }

    private void parseUri(){
        String[] strings=uri.split("\\?");
        requestURI=strings[0];
        if (strings.length>1){
            queryString=strings[1];
            parseParameter(queryString);
        }
        System.out.println("requestURI: "+requestURI);
        System.out.println("queryString: "+queryString);
        System.out.println("parameters: "+parameters);
    }
    /**
     * 解析参数。参数的格式应当是:name1=value1&name2=value2&...
     * 将每一组参数的参数名作为key，参数值作为value存入parameter中
     * /myweb/login?username=%E7%94%B3%E6%B5%A9&password=shanhao123
     * @param line
     */
    private void parseParameter(String line){
        try {
            line= URLDecoder.decode(line,"UTF-8");
            System.out.println(line);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String[] strings=line.split("&");
        for (String para:strings){
            String[] dates=para.split("=");
            parameters.put(dates[0],dates.length>1?dates[1]:null);
        }

    }
    /**
     * 解析消息头
     */
    private void parseHeaders() throws IOException {
        String line;
        while (!(line=readLine()).isEmpty()){//当返回的字符串不为空时循环
            System.out.println("消息头: "+line);
            String[] strings=line.split(":\\s");
            headers.put(strings[0].toLowerCase(),strings[1]);
        }
        System.out.println(headers);
        headers.forEach((k,v)-> System.out.println(k+": "+v));
    }
    /**
     * 解析消息正文
     */
    private void parseContent() throws IOException {
        //当一个请求的请求方式为POST时，则说明应当会包含消息正文
        if ("post".equalsIgnoreCase(method)){
            if (headers.containsKey("content-length")){
                int contentLength=Integer.parseInt(
                        headers.get("content-length")
                );
                System.out.println(">>>>>>>>>>>>contentLength: "+contentLength);
                //根据Content-Length指定的长度创建字节数组
                byte[] data=new byte[contentLength];
                InputStream in=socket.getInputStream();
                in.read(data);
                //根据消息头Content-Type判断正文类型并进行对应的解析
                if (headers.containsKey("content-type")){
                    String contentType=headers.get("content-type");
                    System.out.println("================>contentType: "+contentType);
                    if ("application/x-www-form-urlencoded".equals(contentType)){
                        String line=new String(data, StandardCharsets.ISO_8859_1);
                        System.out.println("正文内容: "+line);
                        parseParameter(line);
                        System.out.println("parameters: "+parameters);
                    }
                }


            }
        }
    }

    private String readLine() throws IOException {
        InputStream in=socket.getInputStream();
        char pre='e',cur='w';
        int d;
        StringBuilder builder=new StringBuilder();
        while ((d=in.read())!=-1){
            cur=(char)d;
            if (pre==13&&cur==10){//13回车，10换行
                break;
            }
            builder.append(cur);
            pre=cur;
        }
        return builder.toString().trim();
    }

    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getProtocol() {
        return protocol;
    }

    public String getHeader(String name){
        return headers.get(name.toLowerCase());
    }

    public String getRequestURI() {
        return requestURI;
    }

    public String getQueryString() {
        return queryString;
    }
    public String getParameter(String name){
        return parameters.get(name);
    }
}
